import React, { useMemo, useState } from 'react';
import {
    DndContext,
    closestCenter,
    KeyboardSensor,
    PointerSensor,
    useSensor,
    useSensors,
    MouseSensor,
    TouchSensor
} from '@dnd-kit/core';
import {
    arrayMove,
    SortableContext,
    sortableKeyboardCoordinates,
    verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { Tooltip, Popconfirm, message } from 'antd'
import styles from './index.less'
import { SortableItem } from '@/components/SortableItem';
import { DeleteFilled, CopyFilled } from '@ant-design/icons';
import moment from 'moment';
import { useModel } from "umi";
import PageItem from './pageitem'



function SortContent({ config, setconfig, height }) {
    const { initialState, setInitialState } = useModel("@@initialState");

    const mouseSensor = useSensor(MouseSensor, {
        coordinateGetter: sortableKeyboardCoordinates,
        activationConstraint: {
            distance: 8,
        },
    });
    const sensors = useSensors(
        useSensor(PointerSensor, {
            activationConstraint: {
                distance: 8,
            },
        }),
        useSensor(KeyboardSensor, {
            activationConstraint: {
                distance: 8,
            },
            coordinateGetter: sortableKeyboardCoordinates,
        }),
        mouseSensor,
    );


    const getrenderheight = (item) => {
        let height = item.height ? item.height : config?.height,
            width = item.width ? item.width : config?.width;
        return (height / width) * 136
    }


    return (
        <DndContext
            sensors={sensors}
            collisionDetection={closestCenter}
            onDragEnd={handleDragEnd}
        >
            <SortableContext
                items={config?.pages.map(it => it.id)}
                strategy={verticalListSortingStrategy}
            >
                {config?.pages.map((it, i) => <SortableItem style={{ width: 136 }} key={it.id} id={it.id}>
                    <div
                        className={`${styles.pageitem} ${it.active ? styles.active : ''}`}
                        style={{ height: getrenderheight(it), overflow: "hidden", width: 136, backgroundColor: it.backgroundColor }}
                        onClick={() => {
                            setInitialState(s => ({ ...s, component: "Canvas", componentConfig: {} }))
                            setconfig(s => {
                                let newcf = { ...s };
                                newcf.pages = newcf.pages ? newcf.pages.map((item, index) => {
                                    item.active = false;
                                    if (item.id == it.id) {
                                        item.active = true;
                                    }
                                    return item
                                }) : [];
                                return newcf
                            })
                        }}
                    >
                        
                        <PageItem page={it}>
                            
                        </PageItem>






                        <div className={styles.actions} onClick={e => e.stopPropagation()}>
                            <Tooltip title="复制该页面">
                                <CopyFilled style={{ color: "#1dac57" }} onClick={() => {
                                    setconfig(s => {
                                        let newcf = JSON.parse(JSON.stringify(s));
                                        newcf.pages.forEach(it => {
                                            it.active = false
                                        })
                                        newcf.pages ? newcf.pages.splice(i + 1, 0, {
                                            ...it,
                                            id: moment().valueOf(),
                                            active: true
                                        }) : [];
                                        return newcf
                                    })
                                }}></CopyFilled>
                            </Tooltip>
                            <Popconfirm placement="bottom" title={"是否删除？"} onConfirm={() => {
                                setconfig(s => {
                                    let newcf = JSON.parse(JSON.stringify(s));
                                    if (s.pages.length == 1) {
                                        message.warn("模板至少需要一个页面！")
                                        return newcf
                                    }
                                    let deleteindex = 0;
                                    newcf.pages = newcf.pages ? newcf.pages.filter((item, index) => {
                                        if (item.id == it.id) {
                                            deleteindex = index;
                                        }
                                        return item.id != it.id
                                    }) : [];

                                    let newpages = [...newcf.pages], pages = [];
                                    if (deleteindex < newpages.length - 1) {
                                        pages = newpages ? newpages.map((item, index) => {
                                            item.active = false;
                                            if (deleteindex == index) {
                                                item.active = true
                                            }
                                            return item
                                        }) : [];

                                    } else {
                                        pages = newpages ? newpages.map((item, index) => {
                                            item.active = false;
                                            if (newpages.length - 1 == index) {
                                                item.active = true;
                                            }
                                            return item
                                        }) : [];

                                    }
                                    newcf.pages = pages
                                    return newcf
                                })
                            }} okText="删除" cancelText="取消">
                                <Tooltip title="删除该页面">
                                    <DeleteFilled style={{ color: "#ff4800", marginLeft: 10 }}></DeleteFilled>
                                </Tooltip>
                            </Popconfirm>
                        </div>
                        <div className={styles.badge}>
                            {i + 1}
                        </div>
                    </div>
                </SortableItem>)}
            </SortableContext>
        </DndContext>
    );

    function handleDragEnd(event) {
        const { active, over } = event;
        if (active.id !== over.id) {
            setconfig((s) => {
                let newcf = { ...s };
                let itemes = newcf.pages ?? [];
                const keyarr = itemes.map(it => it.id);
                const oldIndex = keyarr.indexOf(active.id);
                const newIndex = keyarr.indexOf(over.id);
                let newpages = arrayMove(itemes, oldIndex, newIndex);
                newcf.pages = newpages
                return newcf;
            });
        }
    }
}

export default SortContent;